import styles from './report.less';
import { generate_date_str } from './script/utils.js';
import { useState, useRef } from 'react';
import { get_report_show_info, get_report_detail_info } from './script/report_manager.js';
import {
    echarts_generate_bar_chart_option,
    echarts_generate_line_chart_option} from './script/echarts_config.js';
import ReactEcharts from "echarts-for-react";

import img_arrow_left from './icon/arrow_left.png';
import img_arrow_up from './icon/arrow_up.png';
import img_arrow_down from './icon/arrow_down.png';
import img_ashcan from './icon/ashcan.png';
import img_no_data from './icon/no_data.png';
import img_checkbox_selected from "./icon/checkbox_selected.png";
import img_checkbox_unselected from "./icon/checkbox_unselected.png";

const fs = window.require('fs');

let send_msg_hook; //send msg to index
let set_report_type_hook; //switch page to list or detail

let current_report = '测试报告';
let report_save_path = './src/pages/game/report/';
let report_detail;

function goto_data_collect() {
    send_msg_hook('show_data_collect');
}

function goto_report_detail(name) {
    current_report = name;
    set_report_type_hook('detail');
}

function generate_limit_show_info(min, max, scale, fix_num) {
    let info = "";
    if (fix_num > 0)
        info += ((min / scale).toFixed(fix_num) + '~' + (max / scale).toFixed(fix_num));
    else
        info += ((min / scale) + '~' + (max / scale));
    return info;
}

function generate_report_list(files) {
    let entrys = [];

    for (let i = 0; i < files.length; i++) {
        const { start_time, duration } = get_report_show_info(report_save_path + files[i]);

        let date = new Date(start_time);
        let start_time_str = generate_date_str(date, 'show');
        let duration_str = parseInt(duration / 60).toString() + ':';
        if (duration % 60 > 9)
            duration_str += duration % 60;
        else
            duration_str += ('0' + duration % 60);

        let entry = (
            <li className={styles.report_list_item} key={i}>
                <img src={img_checkbox_unselected} className={styles.report_list_item_checkbox}></img>
                <p className={styles.report_list_item_name} onClick={() => goto_report_detail(files[i])}>{files[i]}</p>
                <p className={styles.report_list_item_info}>
                    <span>开始时间：{start_time_str}</span>
                    <span className={styles.report_list_item_info_interval}>时长：{duration_str}</span>
                </p>
                <div className={styles.report_list_item_split_line}></div>
            </li>
        );
        entrys.push(entry);
    }
    return entrys;
}

function DivReportList() {
    let report_num = 0;
    let report_path = './src/pages/game/report';
    let entrys = [];

    try {
        fs.accessSync(report_path, fs.constants.R_OK);
        let files = fs.readdirSync(report_path);
        report_num = files.length;
        entrys = generate_report_list(files);
    } catch (err) {
    }

    let display_dom = (
        <div className={styles.no_report_tips}>
            <img src={img_no_data} className={styles.no_report_tips_img} alt="no_data"></img>
            <p className={styles.no_report_tips_p}>暂无数据</p>
        </div>
    );

    if (report_num > 0) {
        display_dom = <ul className={styles.report_list_enty}>{entrys}</ul>;
    }

    return (
        <div className={styles.report_list_background}><div className={styles.report_list}>
            <div className={styles.report_list_head}>
                <img className={styles.report_list_back_icon} src={img_arrow_left}
                    onClick={() => goto_data_collect()}></img>
                <p className={styles.report_list_back_info} onClick={() => goto_data_collect()}>返回</p>
                <p className={styles.report_list_split_line}></p>

                <p className={styles.report_list_info}>
                    共有<span className={styles.report_list_num}>{report_num}</span>份测试报告
                </p>
                <img className={styles.delete_icon} src={img_ashcan}></img>
            </div>

            <div className={styles.split_line}></div>

            {display_dom}
        </div></div>
    );
}

const report_data_total_list = [
    {
        title:'FPS数据', use_chart:false, show_data:[
            { title:'屏幕刷新率',   value:'0',  unit:'fps' },
            { title:'平均帧率',     value:'0',  unit:'fps' },
            { title:'Jank',         value:'0',  unit:'/10min' },
            { title:'BigJank',      value:'0',  unit:'/10min' },
            { title:'最大单帧时间', value:'0',  unit:'ms' },
        ],
    },
    {
        title:'CPU信息', use_chart:false, show_data:[
            { title:'Cluster0频率范围', value:'0',  unit:'GHz' },
            { title:'Cluster1频率范围', value:'0',  unit:'GHz' },
            { title:'Cluster2频率范围', value:'0',  unit:'GHz' }
        ],
    },
    {
        title:'CPU使用率', use_chart:true, chart_class:'chart_cpu_usage', chart_option: {},
    },
    {
        title:'GPU数据', use_chart:false, show_data:[
            { title:'频率范围',     value:'0',  unit:'GHz' },
            { title:'平均频率',     value:'0',  unit:'GHz' },
            { title:'最高频占比',   value:'0',  unit:'%' }
        ],
    },
    {
        title:'内存数据', use_chart:false, show_data:[
            { title:'使用范围',     value:'0',  unit:'MB' },
            { title:'频率范围',     value:'0',  unit:'GHz' },
            { title:'平均频率',     value:'0',  unit:'GHz' }
        ],
    },
    {
        title:'系统温度', use_chart:false, show_data:[
            { title:'温度范围',     value:'0',  unit:'℃' },
            { title:'平均温度',     value:'0',  unit:'℃' },
            { title:'高温占比',     value:'0',  unit:'%' }
        ],
    },
    {
        title:'功耗数据', use_chart:false, show_data:[
            { title:'功耗范围',     value:'0',  unit:'maH' },
            { title:'平均功耗',     value:'0',  unit:'maH' }
        ],
    },
    {
        title:'网络数据', use_chart:false, show_data:[
            { title:'带宽范围',     value:'0',  unit:'kbps' },
            { title:'平均带宽',     value:'0',  unit:'kbps' }
        ],
    },
];

let cpu_usage_chart_data = {
    cpu_list: [],
    cpu_usage: [],
    cpu_high_load: [],
};

function update_total_table() {
    report_data_total_list[0].show_data[0].value = report_detail.fps_target;
    report_data_total_list[0].show_data[1].value = report_detail.fps_average.toFixed(1);
    report_data_total_list[0].show_data[2].value = report_detail.fps_jank;
    report_data_total_list[0].show_data[3].value = report_detail.fps_big_jank;
    report_data_total_list[0].show_data[4].value = (report_detail.fps_max_frame_time / 1000).toFixed(1);

    for (let i = 0; i < 3; i++) {
        if (report_detail.cpu_cluster_num > i) {
            report_data_total_list[1].show_data[i].value =
                generate_limit_show_info(report_detail.cpu_min_freq[i], report_detail.cpu_max_freq[i], 1000, 2);
        } else {
            break;
        }
    }

    report_data_total_list[3].show_data[0].value =
        generate_limit_show_info(report_detail.gpu_min_freq, report_detail.gpu_max_freq, 1000, 2);
    report_data_total_list[3].show_data[1].value = (report_detail.gpu_average_freq / 1000).toFixed(2);
    report_data_total_list[3].show_data[2].value = (report_detail.gpu_high_freq_percent).toFixed(1);


    report_data_total_list[5].show_data[0].value =
        generate_limit_show_info(report_detail.temp_min, report_detail.temp_max, 10, 1);
    report_data_total_list[5].show_data[1].value = (report_detail.temp_average / 10).toFixed(1);
    report_data_total_list[5].show_data[2].value = (report_detail.temp_high_percent).toFixed(1);
}

function set_cpu_chart_data(report_detail) {
    cpu_usage_chart_data.cpu_list = [];
    cpu_usage_chart_data.cpu_usage = [];
    cpu_usage_chart_data.cpu_high_load = [];

    for (let i = 0; i < report_detail.cpu_cluster_num; i++) {
        let cpu_index_list = report_detail.cpu_index[i];

        for (let j = 0; j < cpu_index_list.length; j++) {
            let cpu_show_info = 'Cpu' + cpu_index_list[j] + '(CL' + i + ')';
            cpu_usage_chart_data.cpu_list.push(cpu_show_info);

            cpu_usage_chart_data.cpu_usage.push(report_detail.cpu_average_usage[cpu_index_list[j]].toFixed(1));
            cpu_usage_chart_data.cpu_high_load.push(report_detail.cpu_high_load[cpu_index_list[j]].toFixed(1));
        }
    }

    let cpu_data = [
        { name:'CPU 使用率', list:cpu_usage_chart_data.cpu_usage, color_buttom: '#3DB2FF', color_top:'#1879FA' },
        { name:'CPU 高负载占比', list:cpu_usage_chart_data.cpu_high_load, color_buttom: '#FFA634', color_top:'#FF6636'},
    ];
    let cpu_option_y = { user_defined_y: true, min: 0, max: 100, interval: 20, unit: '%'};
    report_data_total_list[2].chart_option =
        echarts_generate_bar_chart_option(cpu_usage_chart_data.cpu_list, cpu_data, cpu_option_y);
}

function DivReportDetailTotal() {
    update_total_table(report_detail);
    set_cpu_chart_data(report_detail);

    const divref = useRef();
    //console.log(divref.current.offsetWidth);

    let data_total_list = [];
    let key_index = 0;
    for (let i = 0; i < report_data_total_list.length; i++) {
        let head_div = (
            <div className={styles.report_data_type} key={key_index++}>
                <div className={styles.report_data_type_line}></div>
                <div className={styles.report_data_type_name}>{report_data_total_list[i].title}</div>
            </div>
        );
        data_total_list.push(head_div);

        let data_div;
        if (report_data_total_list[i].use_chart) {
            data_div = (
                <div className={styles.chart_cpu_usage} key={key_index++}>
                    <ReactEcharts option={report_data_total_list[i].chart_option}
                        style={{width: '100%',  height: '300px'}}/>
                </div>
            );
            data_total_list.push(data_div);
            continue;
        }

        let data_total_item = [];
        for (let j = 0; j < report_data_total_list[i].show_data.length; j++) {
            let item = (
                <div key={key_index++} className={j === 0 ?
                    styles.report_data_total_value_block_first : styles.report_data_total_value_block}>
                    <p className={styles.report_data_total_value_block_title}>
                        {report_data_total_list[i].show_data[j].title}</p>
                    <div className={styles.report_data_total_value_block_value}>
                        <p className={styles.report_data_total_value_block_value_num}>
                            {report_data_total_list[i].show_data[j].value}</p>
                        <p className={styles.report_data_total_value_block_value_unit}>
                            {report_data_total_list[i].show_data[j].unit}</p>
                    </div>
                </div>
            );
            data_total_item.push(item);
        }
        data_div = <div className={styles.report_data_total_value} key={key_index++}>{data_total_item}</div>;
        data_total_list.push(data_div);
    }

    data_total_list.push(<div className={styles.report_data_total_buttom} key={key_index++}></div>);
    return <div className={styles.report_data_total_frame}>{data_total_list}</div>;
}

const report_detail_data_table_index = {
    fps: 0,
    cpu_usage: 1,
    cpu_freq: 2,
    gpu_freq: 3,
    temp: 4,
};

let report_detail_data_table = [
    {
        id:'fps', title: 'FPS', item_list:[],
        option_y:{ user_defined_y: false, unit: ''},
    },
    {
        id:'cpu_usage', title: 'CPU使用率', item_list:[],
        option_y:{ user_defined_y: true, min: 0, max: 100, interval: 20, unit: '%'},
    },
    {
        id:'cpu_freq', title: 'CPU频率', item_list:[],
        option_y:{ user_defined_y: false, unit: 'MHz'},
    },
    {
        id:'gpu_freq', title: 'GPU频率', item_list:[],
        option_y:{ user_defined_y: false, unit: 'MHz'},
    },
    {
        id:'temp', title: '系统温度', item_list:[],
        option_y:{ user_defined_y: true, min: 20, max: 60, interval: 10, unit: '°C'},
    },
];

class line_chart_item {
    constructor(name) {
        this.name = name;
        this.list = [];
    }
}

function update_report_detail_data() {
    for (let data of report_detail_data_table) {
        data.item_list = [];
    }

    let table_index = report_detail_data_table_index;
    let data_item = new line_chart_item('fps');
    data_item.list = report_detail.fps;
    report_detail_data_table[table_index.fps].item_list.push(data_item);

    for (let i = 0; i < report_detail.cpu_cluster_num; i++) {
        let cpu_index_list = report_detail.cpu_index[i];

        let cpu_freq_show_info = 'Cluster' + i + '(';
        for (let j = 0; j < cpu_index_list.length; j++) {
            let cpu_show_info = 'Cpu' + cpu_index_list[j];
            cpu_freq_show_info += cpu_show_info;
            if (j != cpu_index_list.length - 1)
                cpu_freq_show_info += ',';

            data_item = new line_chart_item(cpu_show_info);
            data_item.list = report_detail.cpu_usage[cpu_index_list[j]];
            report_detail_data_table[table_index.cpu_usage].item_list.push(data_item);
        }

        cpu_freq_show_info += ')';
        data_item = new line_chart_item(cpu_freq_show_info);
        data_item.list = report_detail.cpu_freq[i];
        report_detail_data_table[table_index.cpu_freq].item_list.push(data_item);
    }

    data_item = new line_chart_item('GPU频率');
    data_item.list = report_detail.gpu_freq;
    report_detail_data_table[table_index.gpu_freq].item_list.push(data_item);

    data_item = new line_chart_item('系统温度');
    data_item.list = report_detail.temp;
    report_detail_data_table[table_index.temp].item_list.push(data_item);
}

function DivReportDetailCharts() {
    update_report_detail_data();

    let data_chart_list = [];

    let key_index = 0;
    for(let data of report_detail_data_table) {
        let head_div = (
            <div className={styles.report_data_type} key={key_index++}>
                <div className={styles.report_data_type_line}></div>
                <div className={styles.report_data_type_name}>{data.title}</div>
            </div>
        );
        data_chart_list.push(head_div);

        let chart_option = echarts_generate_line_chart_option(data.item_list, data.option_y);
        let chart = <div className={styles.chart_detail} key={key_index++}>
            <ReactEcharts option={chart_option} style={{width: '100%',  height: '260px'}}/></div>;
        data_chart_list.push(chart);
    }

    /* need connect, echarts_connect_charts('report')*/
    return <div className={styles.chart_lists} >{data_chart_list}</div>;
}

function DivReportDetail() {
    report_detail = get_report_detail_info(report_save_path + current_report);
    let date = new Date(report_detail.start_time);
    let start_time_str = generate_date_str(date, 'show');

    return (
        <div className={styles.report_detail}>
            <div className={styles.report_head}>
                <div className={styles.report_head_back}>
                    <img className={styles.report_head_back_icon } src={img_arrow_left}
                        onClick={() => set_report_type_hook('list')}></img>
                    <p className={styles.report_head_back_info} onClick={() => set_report_type_hook('list')}>返回</p>
                    <p className={styles.report_head_split_line}></p>
                    <p className={styles.report_head_title}>测试报告详情</p>
                </div>
                <p className={styles.report_name}>{current_report}</p>
                <p className={styles.report_info}>{'测试时间：' + start_time_str}</p>
            </div>

            <div className={styles.report_detail_data_background}><div className={styles.report_detail_scorll_area}>
                <div className={styles.report_data}>
                    <div className={styles.report_data_total_title}>
                        <p className={styles.report_data_total_title_info}>测试总览</p>
                        <p className={styles.report_data_total_title_control}>收起</p>
                        <img className={styles.report_data_total_title_control_icon} src={img_arrow_up}></img>
                    </div>

                    <DivReportDetailTotal></DivReportDetailTotal>
                </div>

                <div className={styles.report_detail_chart}>
                    <div className={styles.report_data_total_title}>
                        <p className={styles.report_data_total_title_info}>测试详情</p>
                        <p className={styles.report_data_total_title_control}>收起</p>
                        <img className={styles.report_data_total_title_control_icon} src={img_arrow_up}></img>
                    </div>

                    <DivReportDetailCharts></DivReportDetailCharts>
                </div>
            </div></div>
        </div>
    );
}

function PageReport({send_message}) {
    const [report_type, set_report_type] = useState('list');
    set_report_type_hook = set_report_type;
    send_msg_hook = send_message;

    let report_page = <DivReportList></DivReportList>;
    if (report_type === 'detail') {
        report_page = <DivReportDetail></DivReportDetail>;
    }

    return <div className={styles.base}>{report_page}</div>;
};

export default PageReport;